package org.example.demo1;

import java.sql.*;

public class new1 {
    static void main() {
        String url = "jdbc:mysql://localhost:3306/abc?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "123456";
        ResultSet resultSet=null;
        PreparedStatement prep=null;
        Connection con=null;
        int id=0;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
             con = DriverManager.getConnection(url, username, password);
            System.out.println(con);


            String sql="select * from user where username=? and password=?";
             prep = con.prepareStatement(sql);
            prep.setString(1, "admin");
            prep.setString(2, "admin123");
            resultSet = prep.executeQuery();
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("id"));
                System.out.println(resultSet.getString("username"));
                System.out.println(resultSet.getString("email"));
            }


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {//后开的先关
            if (con != null) {
                try {
                    con.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (prep != null) {
                try {
                    prep.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                    System.out.println("数据库连接已关闭。");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
